<?php
/**
 *  绿色情人节，点亮PIKU拿大奖
   活动时间：2014年8月14日-8月17日
 */
class IndexControl extends Control{
	private $model;
	private $uin;
	private $zoneid;
	private $uin_new;
	private $zoneid_new;
	private $s_time='2014-08-14 00:00:00';	//开始时间
	private $e_time='2014-08-17 23:59:59';	//结束时间
	private $arr_coin= array('0x10','0x08','0x800');//奖品包含的货币ID
	private $money = 50;
	private $channelid = 0x0902002F;
	private $tableArr=array('user_info'=>'lsqrj_userinfo','prize_log'=>'lsqrj_prize_log','prize_config'=>'lsqrj_prize_config','money_log'=>'lsqrj_money_log');//表
	function __construct() {
		parent::__construct();
		load_config('commonMain/onload');
		load_model('main');
		$this->model = new MainModel();
		  
		//重新设置活动时间（用于外网、预发布环境）
        if(file_exists(APPLICATION_ROOT.'/config/basic.cfg.php')){
            $BasicCFG=include_once APPLICATION_ROOT.'/config/basic.cfg.php';
            if(!empty($BasicCFG[YEAR][ACT]['s_time']) && !empty($BasicCFG[YEAR][ACT]['e_time'])){
                $this->s_time = $BasicCFG[YEAR][ACT]['s_time'];
                $this->e_time = $BasicCFG[YEAR][ACT]['e_time'];
                $this->money = $BasicCFG[YEAR][ACT]['money'];
            }
        }
	}
	function __destruct() {
		
	}
	
	function index(){
		$view=array();
		$view['loginStatus']=$this->isLogin(0);
		if($view['loginStatus']==1){//登录
			$view['gameinfo']=$this->model->getGameUserInfo($this->uin, $this->zoneid);
			$zones = get_dmz_game_zone();
			$view['ZoneName']	= $zones[$this->zoneid];
			$where="where uin='{$this->uin}' and zoneid='{$this->zoneid}'";
			$view['act_user']=$this->model->getRow($this->tableArr['user_info'], $where);
			
		}
		$view['lotteryList']=$this->model->getRows($this->tableArr['prize_log'],'where `type`=1 order by id desc limit 15');
		$view['bigList']=$this->model->getRows($this->tableArr['prize_log'],'where `type`=1 and bigStatus=1 order by id desc limit 5');
		$view['runkList']=$this->rankList();
		$view['point']=$this->model->getRows($this->tableArr['prize_log'],'where `type`=2 order by id desc limit 5');
		load_view(ACT_PATH.'/index',$view);
	}
	//抽奖
	function lottery(){
		$this->isLogin(1);
		$this->isActTime();
		
		$rows=$this->model->getRows($this->tableArr['prize_config']);
		if(empty($rows)){
			echo json_encode( array('success'=>2,'msg'=>'亲，抽奖失败') );
			return ;
		}
		$proArr=$newItem=array();
		foreach ($rows as &$r){
			$proArr[$r['id']]=$r['probability'];
			$newItem[$r['id']]=$r;
		}
		$id=_pro_rand($proArr);
		$tmpItem=$newItem[$id];
		
		
		$param=array('moeny'=>$this->money,'type'=>1);
		$this->HandleParam($param);
		$id=$this->model->insert_data($this->tableArr['money_log'], $param);
		if(empty($id)){
			echo json_encode( array('success'=>2,'msg'=>'亲，抽奖失败1') );
			return ;
		}
		$moneyStatus=$this->model->modifyUserMoney($this->uin, $this->zoneid, $this->money,$this->channelid,$oldMoney);
		if($moneyStatus===1){
			
			//发物品
			$item=$_SESSION['Gender']==1?$tmpItem['item_id_boy']:$tmpItem['item_id_girl'];            
			$quantity=$tmpItem['item_quantity'];
			
			$param=array('type'=>1,'item_name'=>$tmpItem['item_name'],'item_id'=>$item,'item_usemeans'=>$tmpItem['item_usemeans'],'log_time'=>date('Y-m-d H:i:s'));
			
			if(empty($quantity)){
				$keyTmp=_pro_rand(explode('|',$tmpItem['probability2']));
				$tmpQuantity=explode('|',$tmpItem['item_quantity2']);
				$quantity=$tmpQuantity[$keyTmp];
				if($keyTmp==1){
					$param['bigStatus']=1;
				}
			}
			$param['item_quantity']=$quantity;
			
			$this->sendPrize($param, $item, $quantity);
			if($tmpItem['item_usemeans']==1){
				$sx=$tmpItem['item_quantity']==2147483647?'（永久）':($quantity<86400?'（'.($quantity/3600).'小时）':'（'.($quantity/86400).'天）');
			}else{
				$sx='（'.$quantity.'个）';
			}
			$where="where uin='{$this->uin}' and zoneid='{$this->zoneid}'";
			$u=$this->model->getRow($this->tableArr['user_info'], $where);
			$this->model->update_data($this->tableArr['user_info'], array('point'=>$u['point']+2),$where);
			echo json_encode( array('success'=>1,'msg'=>'亲，成功得到'.$tmpItem['item_name'].' '.$sx,'point'=>$u['point']-$u['use_point']+2) );
		}elseif ($moneyStatus==-1){
			echo json_encode( array('success'=>4,'msg'=>'亲，您的51点余额不足，请充值后再进行游戏哦') );
		}else{
			echo json_encode( array('success'=>2,'msg'=>'亲，抽奖失败2') );
		}
		return ;
	}
	//点亮爱心
	function light(){
		$this->isLogin(1);
		$this->isActTime();
		$id=isset($_GET['k'])?intval($_GET['k']):0;
		$where="where uin='{$this->uin}' and zoneid='{$this->zoneid}'";
		$userArr=$this->model->getRow($this->tableArr['user_info'], $where);
		$itemArr=$this->model->getRows($this->tableArr['prize_config'],"where `type`='{$id}'");
		$gameUser=$this->model->getGameUserInfo($this->uin, $this->zoneid);
		if(empty($itemArr)){
			echo json_encode( array('success'=>2,'msg'=>'亲，失败') );
			return ;
		}
		if(($userArr['point']-$userArr['use_point'])<$itemArr[0]['num']){
			echo json_encode( array('success'=>2,'msg'=>'亲，您的爱心指数（或51点不足）不够哦，暂不能点亮。<br />点亮条件：'.$itemArr[0]['num'].'爱心指数+5 51点   <br />点亮奖励：') );
			return ;
		}
		if($gameUser['Money']<$itemArr[0]['money']){
			echo json_encode( array('success'=>4,'msg'=>'亲，您的51点余额不足，请充值后再进行游戏哦') );
			return ;
		}
		$moenyStatus=$this->model->modifyUserMoney($this->uin, $this->zoneid, $itemArr[0]['money']);
		if($moenyStatus===1){
			$where="where uin='{$this->uin}' and zoneid='{$this->zoneid}'";
			$u=$this->model->getRow($this->tableArr['user_info'], $where);
			$this->model->update_data($this->tableArr['user_info'], array('use_point'=>$u['use_point']+$itemArr[0]['num']),$where);
			$itemName='';
			foreach ($itemArr as &$r){
				$item=$_SESSION['Gender']==1?$r['item_id_boy']:$r['item_id_girl'];
				$quantity=$r['item_quantity'];
				$param=array('type'=>2,'item_name'=>$r['item_name'],'item_id'=>$item,'item_usemeans'=>$r['item_usemeans'],'log_time'=>date('Y-m-d H:i:s'));
				$this->sendPrize($param, $item, $quantity);
				if($r['item_usemeans']==1){
					$sx=$r['item_quantity']==2147483647?'（永久）':($quantity<86400?'（'.($quantity/3600).'小时）':'（'.($quantity/86400).'天）');
				}else{
					$sx='（'.$quantity.'个）';
				}
				$itemName.=$r['item_name'].$sx;
			}
			echo json_encode( array('success'=>1,'msg'=>'亲，恭喜您成功点亮PIKU图标，获得奖励'.$itemName,'point'=>$u['point']-$u['use_point']-$itemArr[0]['num']) );
		}
		
		return ;
	}
	//中奖信息
	function mylist(){
		if($this->isLogin()!=1 ){
			exit(json_encode(array('ajax_html'=>'')));
		}
		
		$ret = '';
		$page=isset($_GET['page'])?intval($_GET['page']):1;
		$row=$this->model->getPageList($this->tableArr['prize_log'],"where uin='{$this->uin}' and zoneid='{$this->zoneid}' and `type`<11",$page,'order by id DESC');
		if(!empty($row['rows'])){
			foreach ($row['rows'] as &$r){
				if($r['item_usemeans']==1){
					$sx=$r['item_quantity']==2147483647?'<strong style="color:red;">（永久）</strong>':($r['item_quantity']<86400?'（'.($r['item_quantity']/3600).'小时）':'（'.($r['item_quantity']/86400).'天）');
				}else{
					$sx='（'.$r['item_quantity'].'个）';
				}
		 		$ret.='<li><span class="date">'.substr($r['log_time'], 0,-3).'</span><span>'.$r['item_name'].$sx.'</span></li>'.PHP_EOL;
				
			}
			$ret.='<script type="text/javascript">';
			$totalPage=empty($row['page']['total_pages'])?0:$row['page']['total_pages'];
			$curretPage=empty($row['page']['current'])?1:$row['page']['current'];
			$ret.="var plb = new PageListBar('plb',{$totalPage},{$curretPage}, './index.php?a=mylist', 1);";
			$ret.='</script>';
 		}else{
 			$totalPage = 0;
 		}

		echo json_encode(array('ajax_html'=>$ret,'total_page'=>$totalPage));
		return ;
	}
	private function rankList(){
		$rows = $this->model->getRows($this->tableArr['user_info'], 'WHERE point>0 ORDER BY getpen DESC LIMIT 10', 'DISTINCT point');
		$ret=array();
		if($rows){
			$i = 0;
			$min = 0;
			$arr_rank = array();
			foreach($rows as $row){
				$i++;
				$arr_rank[$i] = $row['getpen'];
			}
			$min = $arr_rank[$i];
			$j=0;
			$arr = array_flip($arr_rank);
			$rows = $this->model->getRows($this->tableArr['user_info'], "WHERE point>={$min} order by getpen desc",'role_name,point,zoneid');
			$arrZone=get_dmz_game_zone();
			if($rows){
				foreach($rows as $row){
					$ret[$j]=$row;
					$ret[$j]['rank'] = $arr[$row['getpen']];
					$ret[$j]['zone_name']=$arrZone[$row['zoneid']];
					$j++;
				}
			}
		}
		$rows=null;
		return $ret;
	}
	//
	private function sendPrize($param,$item,$quantity){
		$id=$this->model->insert_data($this->tableArr['prize_log'], $param);
		
		if($item=='-1' ||$item=='-2'){
		}else{
		
			if($id){
				$itemArr=explode('|', $item);
				$status='';
				foreach ($itemArr as &$goodes){
					
					$ret = $this->model->sendGameItem( in_array($goodes,$this->arr_coin)?1:0,$this->uin, $this->zoneid,$goodes,$param['item_usemeans'],$quantity);
					$status.=$goodes.':'.$ret.';';
				}
				$this->model->update_data($this->tableArr['prize_log'], array('send_status'=>$status),"where id='{$id}'");
				
			}else{
				exit( json_encode( array('success'=>2,'msg'=>'失败b。') ) );
			}
		}
		return;
	}
	//处理写入数据
	private function HandleParam(&$param){
		$param['uin']=$this->uin;
		$param['zoneid']=$this->zoneid;
		$param['role_name']=$_SESSION['RoleName'];
		$param['account']=$_SESSION['LoginUser'];
		$param['ip']=$_SESSION['IP'];
		return ;
	}
	/**
	 * 
	 * Enter description here ...
	 * @param  $retStauts 0返回值，其它为终于执行
	 */
	private function isLogin($retStauts=0){
		$stat=check_is_login_status();
		if($stat==0){//没有登录
			if($retStauts==0){
				return 0;
			}else{
				echo json_encode(array('success'=>0,'msg'=>'请登录'));
				exit();
			}
			
		}elseif ($stat==2){//已登录没有选择大区
			if($retStauts==0){
				return 2;
			}else{
				echo json_encode(array('success'=>3,'msg'=>'请选择大区'));
				exit();
			}
		}else{
			$this->uin		= $_SESSION['UIN'];
			$this->zoneid	= $_SESSION[DOMAIN_ACT_ZONEID_KEY];
			$ret=ChangeUinByZone($_SESSION['UIN'],$_SESSION[DOMAIN_ACT_ZONEID_KEY]);
			$this->uin_new	=$ret['UIN'];
			$this->zoneid_new=$ret['ZoneID'];
			unset($ret);
			return 1;
		}
	}
	/**
	 * 判断活动时间
	 */
	private function isActTime(){
		$data = array();
		$time = time();
		if($time<strtotime($this->s_time)){
			$stime = date('Y年m月d日', strtotime($this->s_time));
			$etime = date('Y年m月d日', strtotime($this->e_time));
			$data['success'] = 2;
			$data['msg'] = '亲，本活动暂未开始！<br />活动时间:'.$stime.'-'.$etime.'。';
			exit(json_encode($data));
		}elseif($time>=strtotime($this->e_time)){
			$data['success'] = 2;
			$data['msg'] = '亲~本活动已结束哦，请在官网查看其他最新活动。';
			exit(json_encode($data));
		}
	}
/**
	 * 
	 * Enter description here ...
	 * success=5会重新选择
	 */
	function saveSelectZone(){
		if(!check_post_from()){
			echo json_encode(array('success'=>2,'msg'=>'选区出错~'));
			return ;
		}
		
		$login=$this->isLogin(0);
		if($login==0){
			echo json_encode(array('success'=>0,'msg'=>'请登录~'));
			return ;
		}else{
			
			$gamezone=isset($_POST['k'])?intval($_POST['k']):0;
			
			$zone=get_dmz_game_zone();
			if(!array_key_exists($gamezone,$zone)){
				echo json_encode(array('success'=>2,'msg'=>'登录失败，请重试~'));
				return ;
				
			}		
			$_SESSION[DOMAIN_ACT_ZONEID_KEY] = $gamezone;
			$result = $this->model->getGameUserInfo($_SESSION['UIN'], $_SESSION[DOMAIN_ACT_ZONEID_KEY]);
			
			if(empty($result)){
				
				echo json_encode(array('success'=>2,'msg'=>'你选择分区未创建角色，请重新选择！'));
				return ;
				
			}
	
			$_SESSION['RoleName']	= $result['RoleName'];
			$_SESSION['Gender']		= $result['Gender'];
			$_SESSION['Level']		= $result['Level'];
			$_SESSION['Money']		= $result['Money'];
			$_SESSION['IP']			= get_client_ip_from_ns(true);
			
			$datetime=date('Y-m-d H:i:s');
			//插入或更新用户信息
			$sql = "INSERT INTO {$this->tableArr['user_info']} (uin,zoneid,role_level,role_sex,role_name,account,first_ip,last_ip,first_time,last_time)
					VALUE ({$_SESSION['UIN']},{$_SESSION[DOMAIN_ACT_ZONEID_KEY]},{$_SESSION['Level']},{$_SESSION['Gender']},'{$_SESSION['RoleName']}','{$_SESSION['LoginUser']}','{$_SESSION['IP']}','{$_SESSION['IP']}','{$datetime}','{$datetime}') 
					ON DUPLICATE KEY UPDATE last_ip='{$_SESSION['IP']}',last_time='{$datetime}'";
			$this->model->query_sql($sql);
			
			echo json_encode(array('success'=>1,'msg'=>'成功！'));
		}
		return ;
	}
	/**
	 * 登录处理
	 */
	public function save(){
		load_library('pub:core/FOPassPort', false);
		
		if(array_key_exists('jumpto', $_GET)){
			$jumpto = urldecode(htmlspecialchars_decode(($_GET['jumpto'])));
		}else{
			$jumpto = DOMAIN_URL;
		}
		if (stripos($jumpto, 'xx5.com') === false){
			die('error');
		}
		
		$logouturl = 'http://passport.xx5.com/logout.php?gourl='.urlencode(DOMAIN_URL);
		
		if(empty($_SESSION['UIN']) || empty($_SESSION['LoginUser'])){
			session_unset();
			dumpErrorCode('登录失败，请重试！', $logouturl);
		}
		
		header ("Location:" . $jumpto);
		exit();
	}
	
	/**
	 * 退出处理
	 */
	public function logout()
	{
		session_unset();
		session_destroy();
		$gourl = empty($_GET['jumpto']) ? '' : $_GET['jumpto'];
		$gourl = empty($gourl) ? DOMAIN_URL : $gourl;
		$gourl = urlencode(htmlspecialchars_decode($gourl));
		header('Location: http://passport.xx5.com/logout.php?gourl='.$gourl);
		flush();
		exit();
	}
}